/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import vo.TransactionToReportVO;
import ws.login.NormalizedEstablishment;

/**
 *
 * @author Jhovany Amaya
 */
public class CreateReport {

    public CreateReport() {
    }

    public boolean createReport(File fileToSave, List<TransactionToReportVO> transactions, NormalizedEstablishment activeUser, String reportType) {
        boolean ret = true;
        HashMap parameters = new HashMap();
        String path = null;
        if (reportType.equals("Todas las transacciones"))
            path = "src/resources/AllTransactionsReport.jrxml";
        else
            path = "src/resources/GenericReport.jrxml";
            
        String savePath = fileToSave.getPath()+".pdf";
        File fpre = new File(path);
        FileInputStream isPre = null;
        JasperReport jasperReportPre = null;
        JasperPrint jasperPrintPre = null;
        
        JRBeanCollectionDataSource cds = new JRBeanCollectionDataSource(transactions);
        try {
            isPre = new FileInputStream(fpre);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        parameters.put("store", String.valueOf(activeUser.getBrandName()));
        parameters.put("branch", activeUser.getNameEstablishment());
        parameters.put("user", activeUser.getUser());
        
        try {
            jasperReportPre = JasperCompileManager.compileReport(isPre);
        } catch (JRException ex) {
            ex.printStackTrace();
            ret = false;
        }
        try {
            jasperPrintPre = JasperFillManager.fillReport(jasperReportPre, parameters, cds);
        } catch (JRException ex) {
            ex.printStackTrace();
            ret = false;
        }
        try {
            JasperExportManager.exportReportToPdfFile(jasperPrintPre, savePath);
            //JasperViewer.viewReport(jasperPrintPre);
        } catch (Exception ex) {
            ex.printStackTrace();
            ret = false;
        }
        
        return ret;
    }
    
}
